<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>生鲜商城</title>
    <!-- 引入样式 -->
    <link
            rel="stylesheet"
            href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
    />
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="js/jquery.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<el-container id="app">
    <el-header style="height:510px">
        <el-menu
                :default-active="activeIndex"
                class="el-menu-demo"
                mode="horizontal"
                @select="handleSelect"
        >
            <div class="demo-image">
                <div class="block" :key="img.headbg">
                    <el-image
                            style="width: 1920px; height: 440px"
                            :src="img.headbg"
                            :fit="img.headbg">
                    </el-image>
                </div>
            </div>
            <el-menu-item index="11">首页</el-menu-item>
            <el-menu-item index="22">商品</el-menu-item>
            <el-menu-item index="33">限时秒杀</el-menu-item>
            <el-menu-item index="44">领券中心</el-menu-item>
            <el-menu-item index="55">
                <a href="/loginAndRegister" target="_blank" v-if="user.userName=='' "  style="text-decoration: none">登录/注册</a>
                <a href="/myCenter" v-if="user.userName != '' " v-text="user.userName" style="color: #ED2553;text-decoration: none">{{user.userName}}</a>
                <a href="/shoppingCart" v-if="user.userName != '' " class="el-icon-shopping-cart-1"  style="color: #ED2553;text-decoration: none"></a>
            </el-menu-item>
            <el-menu-item index="66">
                <a href="javascript" target="_blank" v-if="user.userName==''"></a>
                <a href="/logout" v-else v-text="logout" style="text-decoration: none">{{logout}}</a>
            </el-menu-item>
        </el-menu>
        <div class="line"></div>
    </el-header>
    <el-main>
        <el-table
                @selection-change="changeFun"
                :data="cartProduct"
                border
                style="width: 100%">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    prop="productId"
                    label="商品编号"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="productName"
                    label="商品名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    label="商品图片">
                <template width="180" slot-scope="scope">
                    <img style="width:80px;height:80px;border:none;" :src="scope.row.img">
                </template>
            </el-table-column>
            <el-table-column
                    label="商品数量"
                    width="210">
                <template width="180" slot-scope="scope">
                    <el-input-number
                            :min="0"
                            v-model.number="scope.row.productNum"
                            autocomplete="off"
                            @change="updateShoppingCart(scope.row)"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column
                    label="商品单价"
                    width="180">
                <template width="180" slot-scope="scope">
                    <span>{{scope.row.productPrice}}元</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="商品总价">
                <template width="180" slot-scope="scope">
                    <span>{{(scope.row.productNum * scope.row.productPrice).toFixed(2)}}元</span>
                </template>
            </el-table-column>
        </el-table>
        <el-row type="flex" class="row-bg" justify="end">

            <el-button style="margin-top: 10px">总金额:{{totalMoney}}</el-button>

            <el-button type="primary" style="margin-top: 10px" round @click="showDialog=true">提交订单</el-button>
        </el-row>

        <!--        提交购物车模态框-->
        <el-dialog
                title="提交购物车"
                :visible.sync="showDialog"
                width="50%"
        >
            <el-form ref="orderInfos" :model="orderInfos" label-width="150px">
                <el-form-item label="商品取货电话">
                    <el-input v-model="orderInfos.ordersPickupPhone"></el-input>
                </el-form-item>
                <el-form-item label="商品取货地址">
                    <!--商品取货地址下拉选项-->
                    <el-select v-model="orderInfos.ordersPickupAddress"
                               placeholder="请选择收货地址"
                    >
                        <el-option
                                v-for="item in address"
                                :key="item.storefrontId"
                                :label="item.storefrontName"
                                :value="item.storefrontName">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="选取优惠券">
                    <!--优惠券下拉选项-->
                    <el-select placeholder="请选取优惠券"
                               v-model="couponId"
                    >
                        <el-option
                                v-for="item in coupons"
                                :key="item.couponId"
                                :value="item.couponId"
                                :label="item.couponName"
                        >
                            <span>优惠力度:{{item.couponDiscount}},过期时间:{{item.couponPastdue}},优惠上限:{{item.couponThreshold}},剩余数量:{{item.userCouponNum}}</span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="商品取货时间">
<!--                    <el-input v-model="orderInfos.ordersPickupTime"></el-input>-->
                    <template>
                        <div class="block">
                            <el-date-picker
                                    v-model="orderInfos.ordersPickupTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    align="right"
                                    >
                            </el-date-picker>
                        </div>
                    </template>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="generateOrder">提交购物车</el-button>
                    <el-button @click="showDialog=false">取消</el-button>
                </el-form-item>

            </el-form>

        </el-dialog>

    </el-main>
</el-container>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            activeIndex: "11",
            productType: [],
            //收货地址
            address: [],
            img: {
                headbg: '/img/bg/banner3.jpg',
                fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
            },
            cartProduct: [],
            //选中的商品信息
            multipleSelection: [],
            showDialog: false,
            couponId:'',
            orderInfos: {
                userId: '',
                ordersPickupPhone: '',
                ordersPickupAddress: '',
                ordersPickupTime: '',
                productId: {},
                userCouponId: {},
            },
            //优惠券信息
            coupons:[],
            user:{
                userName:'',
            },
            logout:'退出登录',
        },
        methods: {
            handleSelect: function (key, keyPath) {
                if(key==11){
                    window.location.href="/"
                }else if(key==22){
                    window.location.href="/toProduct"
                }else if(key==33){
                    window.open("/KillProduct")
                }else if(key==44){
                    window.location.href="/couponCenter"
                }
            },
            generateOrder: function () {
                let vm = this;
                let productId = new Map();
                for (let i = 0; i < vm.multipleSelection.length; i++) {
                    productId.set(vm.multipleSelection[i].productId, vm.multipleSelection[i].productNum);
                }
                let userCouponId = new Map();
                userCouponId.set(vm.orderInfos.userId,vm.couponId);
                localStorage.setItem('address', vm.orderInfos.ordersPickupAddress);
                var orderForm=vm.orderInfos;

                for (let[k,v] of productId) {
                    orderForm.productId[k] = v;
                }
                for (let[k,v] of userCouponId) {
                    orderForm.userCouponId[k] = v;
                }

                $.ajax({
                    url:"/freshmarket/orders/newOrderByCar",
                    data:orderForm,
                    dataType:"json",
                    type:"post",
                    success:function(data){
                        if (data.success) {
                            vm.$message({
                                showClose: true,
                                message: "新增订单成功",
                                type: 'success'
                            });
                        } else {
                            vm.$message({
                                showClose: true,
                                message: resp.data.message,
                                type: 'error'
                            });
                        }
                    }
                })
            },
            //保存被选中的表格数据
            changeFun(val) {
                this.multipleSelection = val;
            },
            //操作数量后发起请求修改用户购物车数据库数据
            updateShoppingCart:function (product) {
                let vm = this;
                let formData = new FormData();
                formData.append("userId",vm.orderInfos.userId);
                formData.append("productId",product.productId);
                formData.append("productNum",product.productNum);
                axios.post("/freshmarket/shopping-car/updateShoppingCart",formData).then(function (resp) {
                    vm.cartProduct = resp.data.data;
                })
            },

        },
        computed: {
            totalMoney: function () {
                let total = 0;
                let vm = this;
                for (let i = 0; i < vm.multipleSelection.length; i++) {
                    total += vm.multipleSelection[i].productNum * vm.multipleSelection[i].productPrice;
                }
                return total.toFixed(2) + '元';
            }
        },
        mounted: function () {
            var vm = this;
            $.ajax({
                url: "/freshmarket/product-type/getList",
                type: "post",
                dataType: "json",
                success: function (data) {
                    if (data.success == true) {
                        vm.productType = data.data;
                    } else {
                        console.log(data.message);
                    }
                },
            });

            //从后端session中获得当前用户并响应给前端
            axios.get("/freshmarket/user/islogin").then(function (resp) {

                // 未成功登录，不能访问购物车重定向到登录页
                if(!resp.data.success && resp.data.code=='404'){
                    vm.$message({
                        showClose: true,
                        message: "请登录后使用购物车",
                        type: 'warning'
                    });
                    window.location.href="/loginAndRegister";
                    return;
                }else if(!resp.data.success){
                    vm.$message({
                        showClose: true,
                        message: resp.data.message,
                        type: 'error'
                    });
                    return;
                }

                //若已登录，执行后续查询操作
                vm.user = resp.data.data;
                //登录后为订单表单用户id赋值
                vm.orderInfos.userId = resp.data.data.userId;
                // vm.orderInfos.userId = 7;
                //获取所有取货地址
                axios.get('/freshmarket/storefront/getStorefront'
                ).then(function (resp) {
                    vm.address = resp.data.data;
                });
                axios.get('/freshmarket/shopping-car/getShoppingCart', {
                    params: {
                        // 此处应该从vm.user中取出userId
                        userId:vm.user.userId,
                        // userId: 7,
                    }
                }).then(function (resp) {
                    vm.cartProduct = resp.data.data;
                });

                //获得用户所有优惠券信息
                axios.get('/freshmarket/shopping-car/getCoupons', {
                    params: {
                        // 此处应该从vm.user中取出userId
                        userId:vm.user.userId,
                        // userId: 7,
                    }
                }).then(function (resp) {
                    if(resp.data.success){
                        vm.coupons = resp.data.data;
                    }else{
                        vm.$message({
                            showClose: true,
                            message: resp.data.message,
                            type: 'error'
                        });
                    }
                });

            });

        },
    });
</script>
</body>
</html>
